package cn.hl.hm.logic.manage;

import cn.hl.hm.constants.WithrawalStatus;
import cn.hl.hm.dao.DriverMapper;
import cn.hl.hm.dao.TBackstageUserEntityMapper;
import cn.hl.hm.dao.WithdrawApplyMapper;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.DriverAmountInfo;
import cn.hl.hm.entity.RechargeRecoardWithdrawal;
import cn.hl.hm.entity.WithdrawApply;
import cn.hl.hm.entity.backstage.TBackstageUserEntity;
import cn.hl.hm.logic.service.IRechargeRecoardWithdrawalService;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.util.List2Map;
import cn.hl.hm.util.paging.PageInfo;
import cn.hl.hm.vo.RechargeRecoardWithdrawalVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.util.*;

/**
 * 后台管理-配载费提现审核
 * Created by xianghan on 17/12/26.
 */
@Service
public class RechargeRecoardWithdrawalLogic {
    private static final Logger logger = LoggerFactory.getLogger(RechargeRecoardWithdrawalLogic.class);
    @Autowired
    IRechargeRecoardWithdrawalService rechargeRecoardWithdrawalService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private WithdrawApplyMapper withdrawApplyMapper;
    @Autowired
    private TBackstageUserEntityMapper backstageUserEntityMapper;

    public Boolean add(String driverPhone, String bankName, String bankCard, String cardholder, Double withdrawalCash,
                       String withdrawalReason, String reportPerson, Integer reportUserId) {
        Driver driver = new Driver();
        driver.setDriverAccount(driverPhone);
        List<Driver> drivers = driverMapper.selectDriver(driver);
        if (drivers != null && drivers.size() > 0 && drivers.get(0)!=null) {
            driver = drivers.get(0);
            DriverAmountInfo selectDriverHistory = driverService.selectDriverHistory(driver.getId());
            if(selectDriverHistory.getCanWithdrawCash().compareTo(new BigDecimal(withdrawalCash))<0) {
                return null;
            }
            TBackstageUserEntity user = backstageUserEntityMapper.selectByPrimaryKey(reportUserId);
            if (user != null) {
                //提现申请审核
                RechargeRecoardWithdrawal withdrawal = rechargeRecoardWithdrawalService.add(driver.getId(),
                        driver.getDriverAccount(), driver.getName(), bankName,
                        bankCard, cardholder, withdrawalCash, withdrawalReason, reportPerson, reportUserId);
                if (withdrawal != null) {
                    //提现记录表
                    WithdrawApply withdrawApply = new WithdrawApply();
                    withdrawApply.setWithdrawalAuditId(withdrawal.getId());
                    withdrawApply.setDriverId(driver.getId());
                    withdrawApply.setDriverName(driver.getName());
                    withdrawApply.setWithdrawCash(new BigDecimal(withdrawalCash));
                    withdrawApply.setWithdrawBankCardNum(bankCard);
                    withdrawApply.setBankCardUserName(cardholder);
                    withdrawApply.setBankCardName(bankName);
                    withdrawApply.setWithdrawInfo(withdrawalReason);
                    withdrawApply.setOpenUser(user.getMailbox());
                    int addApply = driverService.addApply(withdrawApply);
                    if (addApply > 0) {
                        return true;
                    }
                }

            }
        }
        return false;
    }

    public Boolean operationCheck(Integer id, String status, String auditReason, String assessorUsername, Integer assessorUserId) {
        //修改审核状态
        if (rechargeRecoardWithdrawalService.operationCheck(id, status, auditReason, assessorUsername, assessorUserId)) {
            //审核不通过
            if(status.equals("0")) {
                // 退款状态：1，审核中，2，退款成功，3，退款失败
                return auditApply(id, "3");
            }else {
                return true;
            }
        }
        return false;
    }

    public Boolean financialCheck(Integer id, String status, String auditReason, String assessorUsername, Integer assessorUserId) {
        //修改审核状态
        if (rechargeRecoardWithdrawalService.financialCheck(id, status, auditReason, assessorUsername, assessorUserId)) {
            if (status.equals("0")) {
                // 退款状态：1，审核中，2，退款成功，3，退款失败
                return auditApply(id, "3");
            }else {
                return true;
            }
        }
        return false;
    }

    private boolean auditApply(Integer id, String status) {
        //修改提现状态
        WithdrawApply withdrawApply = new WithdrawApply();
        withdrawApply.setWithdrawalAuditId(id);
        List<WithdrawApply> withdrawApplyList = withdrawApplyMapper.selectWithdrawApply(withdrawApply);
        if (withdrawApplyList != null && withdrawApplyList.size() > 0 && withdrawApplyList.get(0) != null) {
            withdrawApply = withdrawApplyList.get(0);
            //提现状态 withdrawStatus 2 通过 3不通过
            if(status.equals(WithrawalStatus.yyshbtg.getStatus()) || status.equals(WithrawalStatus.cwshbtg.getStatus())) {
                withdrawApply.setWithdrawStatus(WithrawalStatus.cwshbtg.getStatus());
            }else if(status.equals(WithrawalStatus.cwshyzf.getStatus())){
                withdrawApply.setWithdrawStatus(WithrawalStatus.yyshtg.getStatus());
            }
            int addApply = driverService.auditApply(withdrawApply);
            if (addApply > 0) {
                return true;
            }
        }
        return false;
    }

    public Boolean confirmPayment(Integer id,
                                  Integer userId) {
        if (rechargeRecoardWithdrawalService.confirmPayment(id, userId)) {
            //修改提现状态
            return auditApply(id, WithrawalStatus.cwshyzf.getStatus());
        }
        return false;
    }

    public Map<String, List> operationAssessors() {
        List<String> list = rechargeRecoardWithdrawalService.operationAssessors();
        Map<String, List> stringListMap = new HashMap<>();
        stringListMap.put("nameList", list);
        return stringListMap;
    }

    public Map<String, List> financialAssessors() {
        List<String> list = rechargeRecoardWithdrawalService.financialAssessors();
        Map<String, List> stringListMap = new HashMap<>();
        stringListMap.put("nameList", list);
        return stringListMap;
    }

    public void selectList(String createTime,
                                                        String status, String driverPhone,
                                                        String driverName, String operationAssessorName,
                                                        String financialAssessorName, Integer pageId, Integer pageCount,ModelMap modelMap) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setCurrentResult(((pageId <= 0) ? 1 : pageId - 1) * pageCount);
        pageInfo.setPageSize(pageCount);
        Map<String, Object> params = new HashMap<>();
        params.put("startTime", createTime);
        params.put("endTime", createTime + " 23:59:59");
        params.put("statusList", Arrays.asList(status.split(",")));
        params.put("driverName", driverName);
        params.put("driverAccount", driverPhone);
        params.put("operationAssessorName", operationAssessorName);
        params.put("financialAssessorName", financialAssessorName);
        pageInfo.setParams(params);
        pageInfo.setDataList(Arrays.asList(status.split(",")));
        List<RechargeRecoardWithdrawal> rechargeRecoardWithdrawalList = rechargeRecoardWithdrawalService.
                list(pageInfo);
        List2Map listUtil = List2Map.getInstance();
        if (listUtil.isNotEmpty(rechargeRecoardWithdrawalList)) {
            List<Driver> drivers = driverService.selectListByIds(listUtil.getFieldList("getDriverId", rechargeRecoardWithdrawalList));
            if (listUtil.isNotEmpty(drivers)) {
                Map<Integer, Driver> driverMap = listUtil.tobeMap("getId", drivers);
                Driver driver = null;
                DriverAmountInfo selectDriverHistory = null;
                List<RechargeRecoardWithdrawalVo> rechargeRecoardWithdrawalVos = new ArrayList<RechargeRecoardWithdrawalVo>();
                RechargeRecoardWithdrawalVo withdrawalVo = null;
                for (RechargeRecoardWithdrawal rechargeRecoardWithdrawal : rechargeRecoardWithdrawalList) {
                    withdrawalVo = new RechargeRecoardWithdrawalVo(rechargeRecoardWithdrawal);
                    driver = driverMap.get(rechargeRecoardWithdrawal.getDriverId());
                    if (driver != null) {
                        withdrawalVo.setIdCard(driver.getDriverLicense());
                        withdrawalVo.setDriverName(driver.getName());
                        selectDriverHistory = driverService.selectDriverHistory(driver.getId());
                        if (selectDriverHistory != null) {
                            withdrawalVo.setRemainCash(selectDriverHistory.getRemainCash());
                            withdrawalVo.setCanWithdrawCash(selectDriverHistory.getCanWithdrawCash());
                        }
                    }
                    rechargeRecoardWithdrawalVos.add(withdrawalVo);
                }
                modelMap.put("rechargeRecoardWithdrawalList",rechargeRecoardWithdrawalVos);
            }
        }
        modelMap.put("pageInfo",pageInfo.build());
    }

    public RechargeRecoardWithdrawalVo selectDetail(Integer rrwId) {
        RechargeRecoardWithdrawal rechargeRecoardWithdrawal = rechargeRecoardWithdrawalService.selectDetail(rrwId);
        if (rechargeRecoardWithdrawal != null) {
            RechargeRecoardWithdrawalVo withdrawalVo = new RechargeRecoardWithdrawalVo(rechargeRecoardWithdrawal);
            Driver driver = driverService.selectByPrimaryKey(rechargeRecoardWithdrawal.getDriverId());
            if (driver != null) {
                withdrawalVo.setIdCard(driver.getIdCard());
                withdrawalVo.setDriverName(driver.getName());
                withdrawalVo.setIdCard(driver.getDriverLicense());
                DriverAmountInfo driverAmountInfo = driverService.selectDriverHistory(driver.getId());
                if (driverAmountInfo != null) {
                    withdrawalVo.setRemainCash(driverAmountInfo.getRemainCash());
                    withdrawalVo.setCanWithdrawCash(driverAmountInfo.getCanWithdrawCash());
                }
            }
            return withdrawalVo;
        }
        return null;
    }

}
